package com.villaday.idf.fragment;


import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.IdRes;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.viewpager.widget.ViewPager;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.atuan.datepickerlibrary.CalendarUtil;
import com.atuan.datepickerlibrary.DatePopupWindowForTeMai;
import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.m7.imkfsdk.KfStartHelper;
import com.moor.imkf.model.entity.CardInfo;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXMiniProgramObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.villaday.idf.R;
import com.villaday.idf.activity.ChouseCheckInDateActivityForTeMai;
import com.villaday.idf.activity.CreatOrderActivity;
import com.villaday.idf.activity.GoodsAndFodderActivityFor3;
import com.villaday.idf.activity.H5Activity;
import com.villaday.idf.adapter.CaiLikeAdapter;
import com.villaday.idf.base.AbsRecyclerViewAdapter;
import com.villaday.idf.base.BaseFragment;
import com.villaday.idf.custom.DividerItemDecoration.RVItemDecoration;
import com.villaday.idf.custom.LoadingDialog;
import com.villaday.idf.custom.mzbanner.MZBannerView;
import com.villaday.idf.custom.mzbanner.holder.MZHolderCreator;
import com.villaday.idf.custom.mzbanner.holder.MZViewHolder;
import com.villaday.idf.model.Favor;
import com.villaday.idf.model.HousesStates;
import com.villaday.idf.model.LoginEntity;
import com.villaday.idf.model.Presell_detail;
import com.villaday.idf.model.Presell_recommend_listEntity;
import com.villaday.idf.model.RefreshtokenEntity;
import com.villaday.idf.model.behaviorsEntity;
import com.villaday.idf.util.BitMapUtil;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.LogeUtil;
import com.villaday.idf.util.OkHttpUtil;
import com.villaday.idf.util.PhoneUtil;
import com.villaday.idf.util.SharedPreferencesUtil;
import com.villaday.idf.util.ToastUtil;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.Unbinder;
import me.bakumon.statuslayoutmanager.library.OnStatusChildClickListener;
import me.bakumon.statuslayoutmanager.library.StatusLayoutManager;

/**
 * 特卖商品
 */
public class GoodsFragment extends BaseFragment implements MZBannerView.BannerPageClickListener, RadioGroup.OnCheckedChangeListener, OkHttpUtil.OnDataListener {

    @BindView(R.id.banner)
    MZBannerView mMZBanner;
    /*@BindView(R.id.cv_countdownViewTest4)
    CountdownView cvCountdownViewTest4;*/
    Unbinder unbinder;
    @BindView(R.id.rg)
    RadioGroup rg;
    @BindView(R.id.view_0)
    View view0;
    @BindView(R.id.view_1)
    View view1;

    @BindView(R.id.tv_h5)
    WebView tvH5;
    @BindView(R.id.tv_page)
    TextView tvPage;
    @BindView(R.id.textView3)
    TextView textView3;


    Unbinder unbinder1;
    @BindView(R.id.tv_zhuan)
    TextView tvZhuan;
    @BindView(R.id.tv_zhuanNum)
    TextView tvZhuanNum;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.tv_delete)
    TextView tvDelete;
    @BindView(R.id.tv_zhe)
    TextView tvZhe;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_zhu)
    TextView tvZhu;
    @BindView(R.id.tv_m)
    TextView tvM;

    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_addr)
    TextView tvAddr;
    Unbinder unbinder2;
    @BindView(R.id.rb_0)
    RadioButton rb0;
    @BindView(R.id.rb_1)
    RadioButton rb1;
    @BindView(R.id.rb_2)
    RadioButton rb2;
    @BindView(R.id.ll)
    LinearLayout ll;
    @BindView(R.id.ll_zhuan)
    LinearLayout llZhuan;
    @BindView(R.id.tv_tg)
    TextView tv_tg;
    @BindView(R.id.tv_buy)
    TextView tv_buy;
    @BindView(R.id.tv_buy1)
    TextView tv_buy1;
    @BindView(R.id.tv_favorite)
    TextView tvFavorite;

    @BindView(R.id.tv_xiajia)
    TextView tvXiajia;
    @BindView(R.id.rv_same)
    RecyclerView rvSame;
    @BindView(R.id.tv_like)
    TextView tvLike;

    @BindView(R.id.ll_head)
    NestedScrollView ll_head;

    @BindView(R.id.look)
    View look;

    @BindView(R.id.tv_kucun)
    TextView tvKucun;


    Unbinder unbinder3;
    private Html.ImageGetter imgGetter;
    private String persellId;
    private LoadingDialog loadingDialog;
    private Gson gson = new GsonBuilder().create();
    private Presell_detail.BodyEntity body;
    private ChangePage changePage;
    private Presell_detail presell_detail;
    private String houseId;
    private StatusLayoutManager statusLayoutManager;

    public GoodsFragment() {
        // Required empty public constructor
    }

    public static GoodsFragment instance(String houseId, String persellId) {
        GoodsFragment homeFragment = new GoodsFragment();
        Bundle bundle = new Bundle();
        bundle.putString("houseId", houseId);

        bundle.putString("persellId", persellId);
        homeFragment.setArguments(bundle);
        return homeFragment;
    }

    @Override
    protected int getViewResId() {
        return R.layout.fragment_goods;
    }

    @Override
    protected void init(View v) {

        houseId = getArguments().getString("houseId");
        mMZBanner.getLayoutParams().height = (int) (PhoneUtil.getPhoneWidth(getContext()) / 1.6);
        mMZBanner.requestLayout();
        RefreshtokenEntity.BodyBean roleInfo =
                SharedPreferencesUtil.getRoleInfo(getContext());
        String roleType = roleInfo.getMember().getType();
        if ("0".equals(roleType)) {
            ll.setVisibility(View.GONE);
            llZhuan.setVisibility(View.GONE);
            tv_tg.setVisibility(View.GONE);
            tv_buy.setVisibility(View.GONE);
            tv_buy1.setVisibility(View.VISIBLE);
        }
        //添加删除线
        tvDelete.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        long time4 = (long) 150 * 24 * 60 * 60 * 1000;
        // cvCountdownViewTest4.start(time4);

        rg.setOnCheckedChangeListener(this);
        //这里面的resource就是fromhtml函数的第一个参数里面的含有的url
        // 获取网路图片
        imgGetter = new Html.ImageGetter() {
            public Drawable getDrawable(String source) {
                Log.i("RG", "source---?>>>" + source);
                Drawable drawable = null;
                URL url;
                try {
                    url = new URL(source);
                    Log.i("RG", "url---?>>>" + url);
                    drawable = Drawable.createFromStream(url.openStream(), ""); // 获取网路图片
                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                }
                drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
                        drawable.getIntrinsicHeight());
                Log.i("RG", "url---?>>>" + url);
                return drawable;
            }
        };
        statusLayoutManager = setupDefaultStatusLayoutManager(ll_head, new OnStatusChildClickListener() {
            @Override
            public void onEmptyChildClick(View view) {

            }

            @Override
            public void onErrorChildClick(View view) {
                loadingDialog = LoadingDialog.newInstance("加载中");
                loadingDialog.show(getActivity().getFragmentManager(), "loading");

                loadData();
            }

            @Override
            public void onCustomerChildClick(View view) {

            }
        });

    }

    public void setChangePage(ChangePage changePage) {

        this.changePage = changePage;
    }


    @Override
    protected void loadData() {

        loadingDialog = LoadingDialog.newInstance("加载中");
        loadingDialog.show(getActivity().getFragmentManager(), "loading");
        persellId = getArguments().getString("persellId");
        OkHttpUtil.getJSON(getContext(), Constant.URL.presell_detail + persellId, this);
        //推荐
        OkHttpUtil.getJSON(getContext(), String.format(Constant.URL.presell_recommend_list, persellId), this);


    }

    private void initview(Presell_detail presell_detail) {
        if (SharedPreferencesUtil.getAgreementTuiJian(getContext())) {

            tvLike.setVisibility(View.VISIBLE);
            rvSame.setVisibility(View.VISIBLE);
        } else {
            tvLike.setVisibility(View.GONE);
            rvSame.setVisibility(View.GONE);

        }
        if (presell_detail.getBody().isHasHouse()) {

        } else {//多店通用
            tvZhu.setVisibility(View.GONE);
            tvAddr.setVisibility(View.GONE);
        }
        //查看库存
        if (TextUtils.isEmpty(presell_detail.getBody().getReservationUrl())) {
            tvKucun.setVisibility(View.GONE);
            look.setVisibility(View.GONE);
        }

        tvFavorite.setSelected(presell_detail.getBody().isFavorite());

        initBanner(presell_detail.getBody().getImageURLs());
        tvM.setText(Html.fromHtml("&yen;"));
        textView3.setText(Html.fromHtml("&yen;"));
        body = presell_detail.getBody();
        tvPrice.setText(body.getCurrentPriceValue());
/*
        tvZhe.setText(body.getOriginalPrice() == 0 ? "0.0折" : new BigDecimal(((double) body.getCurrentPrice() * 10 / (double) body.getOriginalPrice())).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue() + "折");
*/
/*
        tvZhe.setText((((double) body.getCurrentPrice() * 10 / (double) body.getOriginalPrice()) + "").substring(0, 3) + "折");
*/
        tvZhe.setText(TextUtils.isEmpty(body.getDiscount()) || (Double.parseDouble(body.getDiscount()) == 0) ? "" : body.getDiscount() + "折");


        tvDelete.setText(Html.fromHtml("&yen;" + (body.getOriginalPriceValue())));
        tvDelete.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        tvZhu.setText(body.getHouse().getRoomNum() + "室" + body.getHouse().getHallNum() + "厅" + body.getHouse().getBedNum() + "床" + "  |  " + body.getHouse().getAcreage() + "㎡" + "  |  " + (body.getHouse().getHouseType() == 3 ? "可玩" : "宜住") + body.getHouse().getPeopleNum() + "人");
        tvZhuanNum.setText(body.getBrokerAgeAmountValue());
        tvName.setText(body.getName());
        tvTime.setText("截止时间：" + body.getExpiredDate());
        tvAddr.setText(body.getHouse().getAddress());

        //tvH5.setText(Html.fromHtml(body.getHouse().getDetail(), new URLImageGetter(tvH5, getContext()), null));
        tvH5.getSettings().setJavaScriptEnabled(true);
        tvH5.setWebChromeClient(new WebChromeClient());
        tvH5.getSettings().setLoadsImagesAutomatically(true);

        if (body != null) {
            imageFillWidth(tvH5, body.getDetail().replace("<p><br></p><p><br></p>", ""));

        }

        if (body.isOffline()) {
            tvXiajia.setVisibility(View.VISIBLE);
            ll.setVisibility(View.GONE);
            tv_buy.setVisibility(View.GONE);
            tv_buy1.setVisibility(View.GONE);
        }


    }

    /**
     * 处理图片视频填充手机宽度
     *
     * @param webView
     */
    private void imageFillWidth(WebView webView, String htmlStr) {
        //htmlStr.replace("height: 100%","height: auto");
        Document doc = Jsoup.parse(htmlStr);

        //修改视频标签
        Elements embeds = doc.getElementsByTag("embed");
        for (Element element : embeds) {
            //宽度填充手机，高度自适应
            element.attr("width", "100%").attr("height", "auto");
        }
        //webview 无法正确识别 embed 为视频，所以这里把这个标签改成 video 手机就可以识别了
        doc.select("embed").tagName("video");

        //控制图片的大小
        Elements imgs = doc.getElementsByTag("img");
        for (int i = 0; i < imgs.size(); i++) {
            //宽度填充手机，高度自适应
            String width = imgs.get(i).attr("width");
            if (!TextUtils.isEmpty(width)) {
                int phoneWidth = PhoneUtil.getPhoneWidth(getContext());
                try {
                    if (Integer.parseInt(width) > PhoneUtil.PixelsToDip(getContext(), phoneWidth)) {
                        imgs.get(i).attr("width", "100%").attr("height", "auto");
                    }
                } catch (Exception e) {
                    continue;
                }


            } else {
                imgs.get(i).attr("style", "width:  100%; height: auto;");

            }
        }
        //控制图片的大小
        Elements video = doc.getElementsByTag("video");
        for (int i = 0; i < video.size(); i++) {
            //宽度填充手机，高度自适应
            video.get(i).attr("style", "width: 100%; height: auto;");
        }

     /*   //控制图片的大小
        Elements section = doc.getElementsByTag("section");
        for (int i = 0; i < section.size(); i++) {
            //宽度填充手机，高度自适应
            section.get(i).attr("style", "width: 100%; height: auto;");
        }*/

        //加载使用 jsoup 处理过的 html 文本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            webView.setWebContentsDebuggingEnabled(true);
        }

        webView.loadDataWithBaseURL(null, doc.toString(), "text/html", "UTF-8", null);
    }

    private void initBanner(final List<String> imageURLs) {

        //添加Page点击事件
        mMZBanner.setBannerPageClickListener(this);
        //设置是否显示Indicator
        mMZBanner.setIndicatorVisible(false);

        // 设置数据
        tvPage.setText("1/" + imageURLs.size());
        mMZBanner.setPages(imageURLs, new MZHolderCreator<BannerViewHolder>() {
            @Override
            public BannerViewHolder createViewHolder() {
                return new BannerViewHolder();
            }
        });
        mMZBanner.start();
        // 设置页面改变监听器
        mMZBanner.addPageChangeLisnter(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

                try {
                    tvPage.setText(position + 1 + "/" + imageURLs.size());

                }catch (Exception e){
                    Log.e("TAG", "onPageSelected: "+e.getMessage() );
                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });


    }

    @Override
    public void onPause() {
        super.onPause();
        mMZBanner.pause();//暂停轮播
    }

    @Override
    public void onResume() {
        super.onResume();
        mMZBanner.start();//开始轮播
    }

    private void initRGBottomView() {
        view0.setVisibility(View.INVISIBLE);
        view1.setVisibility(View.INVISIBLE);
        //view2.setVisibility(View.INVISIBLE);
    }

    @Override //banner添加Page点击事件
    public void onPageClick(View view, int position) {
//ToastUtil.initToast(getContext(),position+"");
    }


    @Override
    public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {
        if (body == null) {
            return;
        }
        initRGBottomView();
        switch (i) {
            case R.id.rb_0: {//房源详情
                view0.setVisibility(View.VISIBLE);
                if (body != null) {
                    // tvH5.loadDataWithBaseURL("图书名", body.getHouse().getDetail(), "text/html", "utf-8", null);
                    imageFillWidth(tvH5, body.getDetail().replace("<p><br></p><p><br></p>", ""));

                    //tvH5.setText(Html.fromHtml(body.getHouse().getDetail(), new URLImageGetter(tvH5, getContext()), null));

                }

            }
            break;
            case R.id.rb_1: {//购买须知
                view1.setVisibility(View.VISIBLE);
                if (body.getHouse() != null) {
                    // tvH5.loadDataWithBaseURL("图书名", body.getHouse().getVillage().getAround(), "text/html", "utf-8", null);
                    imageFillWidth(tvH5, body.getPurchaseInformation().replace("<p><br></p><p><br></p>", ""));

                    // tvH5.setText(Html.fromHtml(body.getHouse().getVillage().getAround(), new URLImageGetter(tvH5, getContext()), null));
                }
            }
            break;
            case R.id.rb_2: {//小区环境
                // view2.setVisibility(View.VISIBLE);

                if (body.getHouse() != null && body.getHouse().getVillage().getDetail() != null) {
                    //  tvH5.setText(Html.fromHtml(body.getHouse().getVillage().getDetail(), new URLImageGetter(tvH5, getContext()), null));
                    imageFillWidth(tvH5, body.getHouse().getVillage().getDetail().replace("<p><br></p><p><br></p>", ""));

                    // tvH5.loadDataWithBaseURL("图书名", body.getHouse().getVillage().getDetail(), "text/html", "utf-8", null);

                }
            }
            break;
        }
    }

    @Override
    public void onResponse(String url, String json) {
        if (statusLayoutManager != null) {

            statusLayoutManager.showSuccessLayout();
        }
        dismissLoading();
        if (!TextUtils.isEmpty(json)) {
            if ((Constant.URL.presell_detail + persellId).equals(url)) {
                LogeUtil.e("presell_detail", json);
                presell_detail = gson.fromJson(json, Presell_detail.class);
                if ("200".equals(presell_detail.getCode())) {
                    if (presell_detail.getBody() != null) {
                        initview(presell_detail);

                    }


                } else {
                    ToastUtil.initToast(getContext(), presell_detail.getMsg());
                }

            } else if (String.format(Constant.URL.presell_recommend_list, persellId).equals(url)) {
                LogeUtil.e("presell_recommend_list", json);
                Presell_recommend_listEntity recommendList = gson.fromJson(json, Presell_recommend_listEntity.class);
                if ("200".equals(recommendList.getCode())) {
                    initSimilarHouse(recommendList);


                } else {
                    ToastUtil.initToast(getContext(), recommendList.getMsg());
                }
            }else if (String.format(Constant.URL.preSales_states, presell_detail.getBody().getId()).equals(url)) {
                LogeUtil.e("preSales_states", json);
                dismissLoading();
                HousesStates housesStates = gson.fromJson(json, HousesStates.class);
                if ("200".equals(housesStates.getCode())) {
                    if (housesStates.getBody().getMonths() != null) {
                        HousesStates.BodyEntity.MonthsEntity.ListEntity listEntity = housesStates.getBody().getMonths().get(0).getList().get(0);


                       /* createCustomDatePicker(view, "100");


                        for (int i = 0; i < housesStates.getBody().getMonths().size(); i++) {
                          *//*  for (int j = 0; j < 8 - housesStates.getBody().getMonths().get(i).getList().get(0).getDayOfWeek(); j++) {
                                housesStates.getBody().getMonths().get(i).getList().get(j).setFirstInGroup(true);
                            }
                            housesStates.getBody().getMonths().get(i).getList().get(0).setFirst(true);*//*
                            dateCalendar.add(new HousesStates.BodyEntity.MonthsEntity.ListEntity(housesStates.getBody().getMonths().get(i).getList().get(0).getDate(), 1));

                            if (housesStates.getBody().getMonths().get(i).getList().get(0).getDayOfWeek() != 7) {
                                for (int j = 0; j < housesStates.getBody().getMonths().get(i).getList().get(0).getDayOfWeek() - 1; j++) {
                                    dateCalendar.add(new HousesStates.BodyEntity.MonthsEntity.ListEntity(-1));
                                }
                            }
                            dateCalendar.addAll(housesStates.getBody().getMonths().get(i).getList());

                        }

                        dateCheckInAdapter.setData(dateCalendar);*/
                    }
                } else {
                    ToastUtil.initToast(getContext(), housesStates.getMsg());

                }
            }
        }
    }


    @Override
    public void onFailure(String url, String error) {
        ToastUtil.initToast(getContext(), error);
        if (statusLayoutManager != null) {

            statusLayoutManager.showErrorLayout();
        }
        ToastUtil.initToast(getContext(), "网络错误");
        dismissLoading();
    }


    @OnClick({R.id.tv_favorite, R.id.tv_addr, R.id.tv_zx, R.id.tv_buy1, R.id.tv_buy, R.id.tv_tg, R.id.tv_kucun})
    public void onViewClicked(View view) {
        if (body == null) {
            return;
        }
        switch (view.getId()) {
            case R.id.tv_favorite: {//喜欢
                loadingDialog = LoadingDialog.newInstance("操作中");
                loadingDialog.show(getActivity().getFragmentManager(), "loading");

                Favor collect = new Favor(!tvFavorite.isSelected());
                Map<String, Object> map = new HashMap<>();
                OkHttpUtil.postJson(getContext(), String.format(Constant.URL.member_favor, "52", body.getId()), collect, map, new OkHttpUtil.OnDataListener() {
                    @Override
                    public void onResponse(String url, String json) {
                        dismissLoading();

                        LogeUtil.e("member_favor", json);
                        behaviorsEntity behaviorsEntity = gson.fromJson(json, com.villaday.idf.model.behaviorsEntity.class);

                        if (behaviorsEntity.getBody().getStatus() == 1) {
                            tvFavorite.setSelected(!tvFavorite.isSelected());

                            ToastUtil.initToast(getContext(), tvFavorite.isSelected() ? "已喜欢" : "已取消喜欢");

                        } else if (behaviorsEntity.getBody().getStatus() == 0) {

                            ToastUtil.initToast(getContext(), "操作失败");

                        } else {
                            ToastUtil.initToast(getContext(), "操作失败");

                        }

                    }

                    @Override
                    public void onFailure(String url, String error) {

                    }
                });
            }

            break;
            case R.id.tv_zx:
               /* Intent intent1 = new Intent(Intent.ACTION_DIAL);
                Uri data = Uri.parse("tel:" + "0755-26657792");
                intent1.setData(data);
                startActivity(intent1);*/
                if (body.getImShareDTO() == null) {
                    return;
                }

                KfStartHelper helper = new KfStartHelper(getActivity());
                LoginEntity userInfo = SharedPreferencesUtil.getUserInfo(getContext());
                CardInfo ci = null;
                try {
                    ci = new
                            CardInfo(body.getImShareDTO().getImageURL(),
                            body.getImShareDTO().getTitle(),
                            body.getImShareDTO().getSurrounding(),
                            PhoneUtil.handleBalance((Long.parseLong(body.getImShareDTO().getPrice()) / 100 + ""), 2),
                            body.getImShareDTO().getLinkURL());
                } catch (Exception e) {
                    e.printStackTrace();
                }

                //设置card
                helper.setCard(ci);
                //设置参数初始化
                helper.initSdkChat("com.villaday.idf.7mss",
                        userInfo.getBody().getMember().getNickName() + "",
                        userInfo.getBody().getMember().getId() + "");

                break;
            case R.id.tv_buy:
            case R.id.tv_buy1:
                if (presell_detail != null && presell_detail.getBody() != null) {

                    if (presell_detail.getBody().isAllowSelectDate()){
                        if (TextUtils.isEmpty(presell_detail.getBody().getBookingWarn())) {
                            Intent intent3 = new Intent(getContext(), ChouseCheckInDateActivityForTeMai.class);

                            intent3.putExtra("type", 7);
                            intent3.putExtra("activity_id", presell_detail.getBody().getId());
                            intent3.putExtra("activity_type", 13);
                            intent3.putExtra("hasHouse", body.isHasHouse());

                            //intent3.putExtra("hasHouse", mYHousesEntity.getBody().is);


                            startActivity(intent3);


                        } else {
                            ToastUtil.initToast(getContext(), presell_detail.getBody().getBookingWarn());

                        }
                    }else {
                        if (presell_detail != null && presell_detail.getBody() != null) {
                            if (TextUtils.isEmpty(presell_detail.getBody().getBookingWarn())) {
                                Intent intent3 = new Intent(getContext(), CreatOrderActivity.class);
                                intent3.putExtra("type", 7);
                                intent3.putExtra("activity_id", presell_detail.getBody().getId());
                                intent3.putExtra("activity_type", 13);
                                intent3.putExtra("hasHouse", body.isHasHouse());

                                startActivity(intent3);
                            } else {
                                ToastUtil.initToast(getContext(), presell_detail.getBody().getBookingWarn());

                            }
                        }
                    }

                }




                break;
            case R.id.tv_tg:
                changePage.changePage();
                break;
            case R.id.tv_addr://地图

                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                Uri content_url = Uri.parse(String.format(Constant.URL.MapDiTu, presell_detail.getBody().getHouse().getLocation().getLatitude() + "", presell_detail.getBody().getHouse().getLocation().getLongitude() + "", presell_detail.getBody().getHouse().getAddress(), presell_detail.getBody().getHouse().getLocation().getCity()));
                intent.setData(content_url);
                startActivity(intent);
                break;
            case R.id.tv_kucun: {//查看库存及可约日期

                if (presell_detail != null && presell_detail.getBody() != null) {
                    Intent intent1 = new Intent(getContext(), H5Activity.class);
                    intent1.putExtra("title", "爱订房");
                    intent1.putExtra("url", presell_detail.getBody().getReservationUrl());
                    startActivity(intent1);
                }


            }
            break;
        }
    }
    private void getCalendar() {
        Map<String, String> datemap = new HashMap<>();

        datemap.clear();
        datemap.put("month", "");
        datemap.put("size", 3 + "");
        OkHttpUtil.getJSON(getContext(), String.format(Constant.URL.preSales_states, presell_detail.getBody().getId()), datemap, this);
    }
    //日历
    private int startGroup = -1;
    private int endGroup = -1;
    private int startChild = -1;
    private int endChild = -1;
    private String checkInDate = "";
    private String checkOutDate = "";

    private void createCustomDatePicker(View view, final String result) {
        new DatePopupWindowForTeMai
                .Builder(getActivity(), Calendar.getInstance().getTime(), view)
                .setInitSelect(startGroup, startChild, endGroup, endChild)
                .setEndDateBuy("")
                .setStartDateBuy("")
                .setPrice("1000")
                //.setInitSelect(-1, -1, -1, -1)

                .setInitDay(false)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (v.getId() == R.id.btn_clear) {
                            checkInDate = "";
                            checkOutDate = "";
                            startGroup = -1;
                            startChild = -1;
                            endGroup = -1;
                            endChild = -1;

                        }
                    }
                })
                .setDateOnClickListener(new DatePopupWindowForTeMai.DateOnClickListener() {
                    @Override
                    public void getDate(String startDate, String endDate, int startGroupPosition, int startChildPosition, int endGroupPosition, int endChildPosition) {
                        startGroup = startGroupPosition;
                        startChild = startChildPosition;
                        endGroup = endGroupPosition;
                        endChild = endChildPosition;

                        checkInDate = startDate;
                        checkOutDate = endDate;
                        String mStartTime = CalendarUtil.FormatDate_MD(startDate);
                        String mEndTime = CalendarUtil.FormatDate_MD(endDate);

                        Intent intent3 = new Intent(getContext(), CreatOrderActivity.class);
                        intent3.putExtra("type", 7);
                        intent3.putExtra("activity_id", presell_detail.getBody().getId());
                        intent3.putExtra("activity_type", 13);
                        intent3.putExtra("hasHouse", body.isHasHouse());

                        startActivity(intent3);
                    }
                }).builder();
    }

    public static class BannerViewHolder implements MZViewHolder<String> {
        private SimpleDraweeView mImageView;

        @Override
        public View createView(Context context) {
            // 返回页面布局
            View view = LayoutInflater.from(context).inflate(R.layout.banner_item, null);
            mImageView = (SimpleDraweeView) view.findViewById(R.id.banner_image);
            return view;
        }

        @Override
        public void onBind(Context context, int position, String data) {
            // 数据绑定
            // mImageView.setImageURI(new Uri.Builder().scheme("res").path(String.valueOf(data)).build());
            mImageView.setImageURI(data);
        }
    }

    public class URLImageGetter implements Html.ImageGetter {
        Context c;
        TextView tv_image;
        private List<Target> targets = new ArrayList<>();

        public URLImageGetter(TextView t, Context c) {
            this.tv_image = t;
            this.c = c;
            tv_image.setTag(targets);
        }

        @Override
        public Drawable getDrawable(final String source) {
            final URLDrawable urlDrawable = new URLDrawable();
            final Target target = new Target() {
                @Override
                public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                    Drawable drawable = new BitmapDrawable(bitmap);
                    drawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight());
                    urlDrawable.setDrawable(drawable);
                    urlDrawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight());
                    tv_image.invalidate();
                    tv_image.setText(tv_image.getText());
                }

                @Override
                public void onBitmapFailed(Exception e, Drawable errorDrawable) {
                    errorDrawable.setBounds(0, 0, errorDrawable.getIntrinsicWidth(), errorDrawable.getIntrinsicHeight());
                    urlDrawable.setBounds(0, 0, errorDrawable.getIntrinsicWidth(), errorDrawable.getIntrinsicHeight());
                    urlDrawable.setDrawable(errorDrawable);
                    tv_image.invalidate();
                }


                @Override
                public void onPrepareLoad(Drawable placeHolderDrawable) {
                    placeHolderDrawable.setBounds(0, 0, placeHolderDrawable.getIntrinsicWidth(), placeHolderDrawable.getIntrinsicHeight());
                    urlDrawable.setBounds(0, 0, placeHolderDrawable.getIntrinsicWidth(), placeHolderDrawable.getIntrinsicHeight());
                    urlDrawable.setDrawable(placeHolderDrawable);
                    tv_image.invalidate();
                }
            };

            targets.add(target);
            loadPlaceholder(c, source, target);
            return urlDrawable;
        }

        public void loadPlaceholder(Context context, String url, Target target) {

            Picasso picasso = new Picasso.Builder(context).loggingEnabled(true).build();
            picasso.load(url)
                    .placeholder(R.drawable.img_order)
                    .error(R.drawable.img_order)
                    .into(target);
        }


    }


    public class URLDrawable extends BitmapDrawable {
        private Drawable drawable;

        @Override
        public void draw(Canvas canvas) {
            if (drawable != null) {
                drawable.draw(canvas);
            }
        }

        public void setDrawable(Drawable drawable) {
            this.drawable = drawable;
        }

    }

    private void dismissLoading() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }

    }

    public interface ChangePage {
        void changePage();
    }

    private void initSimilarHouse(final Presell_recommend_listEntity body) {
        if (body.getBody() == null || body.getBody().size() == 0) {
            tvLike.setVisibility(View.GONE);
            rvSame.setVisibility(View.GONE);
        } else {
            if (SharedPreferencesUtil.getAgreementTuiJian(getContext())) {

                tvLike.setVisibility(View.VISIBLE);
                rvSame.setVisibility(View.VISIBLE);
            } else {
                tvLike.setVisibility(View.GONE);
                rvSame.setVisibility(View.GONE);

            }


        }

        rvSame.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        CaiLikeAdapter homeDetailsSameAdapter = new CaiLikeAdapter(getContext());
        rvSame.setAdapter(homeDetailsSameAdapter);

        rvSame.addItemDecoration(new RVItemDecoration(LinearLayoutCompat.HORIZONTAL, PhoneUtil.dp2px(getContext(), 7), getResources().getColor(R.color.colorWhite), PhoneUtil.dp2px(getContext(), 7)));
        homeDetailsSameAdapter.setFullScreen(true);
        homeDetailsSameAdapter.setOnItemClickListener(new AbsRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                Intent intent = new Intent(getContext(), GoodsAndFodderActivityFor3.class);
                intent.putExtra("type", 0);
                intent.putExtra("persellId", body.getBody().get(position).getId());
                intent.putExtra("houseId", body.getBody().get(position).getId());
                startActivity(intent);

            }
        });
        List<Presell_recommend_listEntity.BodyBean> similarHouseList = new ArrayList<>();
        similarHouseList.addAll(body.getBody());
        homeDetailsSameAdapter.setData(similarHouseList);
    }

    public boolean getLikeStata() {

        return tvFavorite.isSelected();
    }

    public void shareXCX() {

        if (presell_detail != null) {

            new Thread(new Runnable() {
                @Override
                public void run() {
                    Presell_detail.BodyEntity.ShareResponseEntity shareResponse = presell_detail.getBody().getShareResponse();


                    File file = saveImageToSdCard(getContext(), shareResponse.getImageUrl());

                    String fileName = file.getAbsolutePath();


                    WXMiniProgramObject miniProgramObj = new WXMiniProgramObject();
                    miniProgramObj.webpageUrl = shareResponse.getLink(); // 兼容低版本的网页链接
/*
        miniProgramObj.miniprogramType = WXMiniProgramObject.MINIPTOGRAM_TYPE_RELEASE;// 正式版:0，测试版:1，体验版:2
*/
                    miniProgramObj.userName = shareResponse.getMiniAppId();     // 小程序原始id
                    miniProgramObj.path = shareResponse.getPath();            //小程序页面路径
                    WXMediaMessage msg = new WXMediaMessage(miniProgramObj);
                    msg.title = shareResponse.getTitle();                 // 小程序消息title
                    msg.description = shareResponse.getDesc();
                    Bitmap bitmap = BitMapUtil.getBitmap(fileName);

                    msg.thumbData = BitMapUtil.compressBitmap(bitmap, 100 * 1024);// 小程序消息desc

                    SendMessageToWX.Req req = new SendMessageToWX.Req();
                    req.transaction = "webpage";
                    req.message = msg;
                    req.scene = SendMessageToWX.Req.WXSceneSession;  // 目前支持会话
                    IWXAPI api = WXAPIFactory.createWXAPI(getContext(), Constant.ID.WeChat_APP_ID, false);

                    api.sendReq(req);
                }
            }).start();

        }


    }

    //根据网络图片url路径保存到本地
    public File saveImageToSdCard(Context context, String image) {
        boolean success = false;
        File file = null;
        try {

            file = createStableImageFile(context);
            Bitmap bitmap = null;
            URL url = new URL(image);
            HttpURLConnection conn = null;
            conn = (HttpURLConnection) url.openConnection();
            InputStream is = null;
            is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);

            FileOutputStream outStream;

            outStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
            outStream.flush();
            outStream.close();
            success = true;
            //MediaStore.Images.Media.insertImage(context.getContentResolver(), image, file.getName(), "你对图片的描述");

        } catch (Exception e) {
            e.printStackTrace();
        }

        if (success) {

            return file;
        } else {
            return null;
        }
    }

    //创建本地保存路径
    public static File createStableImageFile(Context context) throws IOException {

        String imageFileName = "shareXCX" + System.currentTimeMillis() + ".jpg";
        File storageDir = context.getExternalCacheDir();
        File image = new File(storageDir, imageFileName);
        return image;
    }
}
